<template>
  <div class="ai-assistant-container">
    <q-card class="ai-chat-card">
      <q-card-section class="bg-primary text-white">
        <div class="row items-center">
          <div class="col">
            <div class="text-h5 q-mb-xs">AI 助手</div>
            <div class="text-caption">有任何问题都可以向我提问</div>
          </div>
          <div class="col-auto">
            <q-btn flat round icon="refresh" @click="resetChat" size="sm">
              <q-tooltip>清空对话</q-tooltip>
            </q-btn>
          </div>
        </div>
      </q-card-section>

      <!-- 聊天消息区域 -->
      <q-card-section class="chat-container q-pa-none" ref="chatContainer">
        <q-scroll-area ref="scrollArea" class="full-height">
          <div class="q-pa-md">
            <!-- 欢迎消息 -->
            <div v-if="chatMessages.length === 0" class="welcome-container text-center q-pa-lg">
              <q-avatar size="80px" class="q-mb-md">
                <img src="/pic/1.jpg" alt="AI Avatar">
              </q-avatar>
              <div class="text-h6 q-mb-md">欢迎使用 AI 助手</div>
              <div class="text-body1 q-mb-lg">我可以回答你的问题，提供信息，或者帮助你解决问题。</div>
              <div class="row q-col-gutter-md justify-center">
                <div class="col-12 col-sm-auto" v-for="(suggestion, index) in suggestions" :key="index">
                  <q-btn
                    outline
                    color="primary"
                    class="full-width"
                    :label="suggestion"
                    @click="sendMessage(suggestion)"
                  />
                </div>
              </div>
            </div>

            <!-- 消息列表 -->
            <template v-else>
              <div
                v-for="(message, index) in chatMessages"
                :key="index"
                class="q-mb-md chat-message"
                :class="{ 'user-message': message.sender === 'user', 'ai-message': message.sender === 'ai' }"
              >
                <div class="row no-wrap items-start">
                  <q-avatar v-if="message.sender === 'ai'" size="40px" class="q-mr-sm">
                    <img src="/pic/1.jpg" alt="AI Avatar">
                  </q-avatar>
                  
                  <div class="message-content">
                    <div class="message-bubble">
                      <div v-if="message.isTyping" class="typing-indicator">
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                      <div v-else v-html="formatMessage(message.text)"></div>
                    </div>
                    <div class="text-caption text-grey-7 q-mt-xs message-time">
                      {{ message.time }}
                    </div>
                  </div>
                  
                  <q-avatar v-if="message.sender === 'user'" size="40px" class="q-ml-sm">
                    <img src="/pic/1.jpg" alt="User Avatar">
                  </q-avatar>
                </div>
              </div>
            </template>
          </div>
        </q-scroll-area>
      </q-card-section>

      <!-- 输入框区域 -->
      <q-separator />
      <q-card-section>
        <q-form @submit="sendUserMessage" class="row items-center">
          <div class="col">
            <q-input
              v-model="userInput"
              outlined
              placeholder="输入您的问题..."
              dense
              autofocus
              @keydown.enter.prevent="sendUserMessage"
              :disable="isAiResponding"
              :loading="isAiResponding"
            >
              <template v-slot:prepend>
                <q-icon name="message" />
              </template>
            </q-input>
          </div>
          <div class="col-auto q-ml-sm">
            <q-btn
              type="submit"
              color="primary"
              icon="send"
              round
              :disable="!userInput.trim() || isAiResponding"
            />
          </div>
        </q-form>
      </q-card-section>
    </q-card>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from 'vue'
import { date } from 'quasar'

// 滚动区域引用
const scrollArea = ref(null)
const chatContainer = ref(null)

// 用户输入
const userInput = ref('')
const isAiResponding = ref(false)

// 聊天消息列表
const chatMessages = ref([])

// 对话历史
const messageHistory = ref([
  { role: 'system', content: '你是一个有帮助的智能助手，可以回答各种问题并提供专业的建议。' }
])

// 建议问题
const suggestions = [
  '什么是Vue 3?',
  '如何优化网站性能?',
  '介绍一下你自己',
  '如何学习前端开发?'
]

// 格式化消息，支持换行和简单的Markdown
const formatMessage = (text) => {
  if (!text) return ''
  
  // 处理换行
  let formatted = text.replace(/\n/g, '<br>')
  
  // 处理粗体 **text**
  formatted = formatted.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理斜体 *text*
  formatted = formatted.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  return formatted
}

// 发送用户消息
const sendUserMessage = async () => {
  const message = userInput.value.trim()
  if (!message || isAiResponding.value) return
  
  // 添加用户消息
  addMessage('user', message)
  userInput.value = ''
  
  // 更新对话历史
  messageHistory.value.push({ role: 'user', content: message })
  
  // 滚动到底部
  await scrollToBottom()
  
  // 模拟AI正在输入
  isAiResponding.value = true
  
  // 添加AI正在输入的临时消息
  const typingMessageIndex = chatMessages.value.length
  chatMessages.value.push({
    sender: 'ai',
    text: '',
    isTyping: true,
    time: formatTime()
  })
  
  // 滚动到底部显示输入指示器
  await scrollToBottom()
  
  try {
    // 调用通义千问API
    const apiKey = 'sk-11684e23a93c45eca49b9f6f171889fa'
    const apiUrl = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
    
    const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify({
        model: 'qwen-plus',
        messages: messageHistory.value
      })
    })
    
    if (!response.ok) {
      throw new Error(`API请求失败: ${response.status} ${response.statusText}`)
    }
    
    const data = await response.json()
    
    // 获取AI回复
    const aiReply = data.choices[0].message.content
    
    // 更新对话历史
    messageHistory.value.push({ role: 'assistant', content: aiReply })
    
    // 移除正在输入的消息
    chatMessages.value.splice(typingMessageIndex, 1)
    
    // 添加AI回复
    addMessage('ai', aiReply)
  } catch (error) {
    console.error('API调用出错:', error)
    
    // 移除正在输入的消息
    chatMessages.value.splice(typingMessageIndex, 1)
    
    // 添加错误消息
    addMessage('ai', '抱歉，我遇到了一些问题，请稍后再试。错误信息: ' + error.message)
  } finally {
    isAiResponding.value = false
    
    // 滚动到底部
    scrollToBottom()
  }
}

// 添加消息到聊天记录
const addMessage = (sender, text) => {
  chatMessages.value.push({
    sender,
    text,
    isTyping: false,
    time: formatTime()
  })
}

// 通过预设问题发送消息
const sendMessage = (message) => {
  userInput.value = message
  sendUserMessage()
}

// 格式化时间
const formatTime = () => {
  return date.formatDate(new Date(), 'HH:mm')
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (scrollArea.value) {
    scrollArea.value.setScrollPosition('vertical', 100000)
  }
}

// 重置聊天
const resetChat = () => {
  chatMessages.value = []
  messageHistory.value = [
    { role: 'system', content: '你是一个有帮助的智能助手，可以回答各种问题并提供专业的建议。' }
  ]
}

// 监听消息变化，自动滚动到底部
watch(chatMessages, () => {
  scrollToBottom()
}, { deep: true })

// 组件挂载后的处理
onMounted(() => {
  // 可选：添加欢迎消息
  // addMessage('ai', '你好！我是AI助手，有什么可以帮到你的吗？')
})
</script>

<style scoped>
.ai-assistant-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  height: 100%;
}

.ai-chat-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 180px);
  display: flex;
  flex-direction: column;
}

.chat-container {
  flex: 1;
  overflow: hidden;
  position: relative;
}

.full-height {
  height: 100%;
}

.chat-message {
  display: flex;
  flex-direction: column;
}

.user-message {
  align-items: flex-end;
}

.ai-message {
  align-items: flex-start;
}

.message-content {
  max-width: 80%;
}

.user-message .message-content {
  margin-left: auto;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  word-break: break-word;
}

.user-message .message-bubble {
  background-color: var(--q-primary);
  color: white;
  border-top-right-radius: 4px;
}

.ai-message .message-bubble {
  background-color: #f0f0f0;
  color: #333;
  border-top-left-radius: 4px;
}

.message-time {
  font-size: 0.7rem;
  margin-top: 4px;
}

.user-message .message-time {
  text-align: right;
}

.welcome-container {
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: 12px;
  padding: 30px;
}

/* 打字动画效果 */
.typing-indicator {
  display: flex;
  align-items: center;
}

.typing-indicator span {
  height: 8px;
  width: 8px;
  float: left;
  margin: 0 1px;
  background-color: #9E9EA1;
  display: block;
  border-radius: 50%;
  opacity: 0.4;
}

.typing-indicator span:nth-of-type(1) {
  animation: 1s blink infinite 0.3333s;
}

.typing-indicator span:nth-of-type(2) {
  animation: 1s blink infinite 0.6666s;
}

.typing-indicator span:nth-of-type(3) {
  animation: 1s blink infinite 0.9999s;
}

@keyframes blink {
  50% {
    opacity: 1;
  }
}

@media (max-width: 600px) {
  .ai-assistant-container {
    padding: 10px;
  }
  
  .ai-chat-card {
    height: calc(100vh - 140px);
  }
  
  .message-content {
    max-width: 90%;
  }
}
</style> 